package com.joysuch.wwyt.bp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.bean.investigate.BpInvestigateTaskQueryBean;
import com.joysuch.wwyt.bp.bean.investigate.vo.BpInvestigateTaskHisVO;
import com.joysuch.wwyt.bp.entity.BpInvestigateTaskHis;
import com.joysuch.wwyt.bp.mapper.BpInvestigateTaskHisMapper;
import com.joysuch.wwyt.bp.service.BpInvestigateTaskHisService;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author heqifeng
 * @since 2022-06-08
 */
@Service
public class BpInvestigateTaskHisServiceImpl extends ServiceImpl<BpInvestigateTaskHisMapper, BpInvestigateTaskHis> implements BpInvestigateTaskHisService {

    @Autowired
    private BaseUserDao baseUserDao;

    @Override
    public Page<BpInvestigateTaskHisVO> pageByCheckPlanId(BpInvestigateTaskQueryBean queryBean) {

        String checkUserName = queryBean.getCheckUserName();
        List<Long> userIds = Lists.newArrayList();
        if (!StringUtils.isEmpty(checkUserName)) {
            List<Long> ids = baseUserDao.findByNameLike(checkUserName);
            // 查无此人
            if (CollectionUtil.isEmpty(ids)) {
                return new Page<BpInvestigateTaskHisVO>();
            }

            userIds.addAll(ids);
        }

        Page<BpInvestigateTaskHisVO> page = new Page<>(queryBean.getPage() + 1, queryBean.getSize());

        Page<BpInvestigateTaskHisVO> bpInvestigateRecordHisVOPage = this.baseMapper.pageBpInvestigateTaskHis(page, queryBean, userIds);

        convertUser(bpInvestigateRecordHisVOPage.getRecords());

        return bpInvestigateRecordHisVOPage;

    }

    private void convertUser(List<BpInvestigateTaskHisVO> taskHisVOList) {

        List<Long> userIds = taskHisVOList.stream().map(BpInvestigateTaskHisVO::getUserId).distinct().collect(Collectors.toList());

        if (CollectionUtil.isEmpty(userIds)) {
            return;
        }

        Map<Long, String> userMap = baseUserDao.findAllById(userIds).stream().collect(Collectors.toMap(r -> r.getId(), r -> r.getRealName()));

        taskHisVOList.forEach(task -> {
            task.setUserName(userMap.get(task.getUserId()));
        });

    }

    @Override
    public List<BpInvestigateTaskHis> getFinishOldSourceTask(Long lastTaskId) {
        return baseMapper.getFinishOldSourceTask(lastTaskId);
    }

}
